using System;
using System.IO;
using System.Text;

namespace Read.Utility
{
    /* 2011-04-06 Telesa */

    /// <summary>
    /// 日志操作类
    /// </summary>
    public class Logs
    {
        private Exception _exc;
        private string _host, _path, _queryString;
        public Logs(Exception ex)
        {
            _exc = ex;
        }
        public Logs(Exception ex, string host, string path, string queryString)
        {
            _exc = ex;
            _host = host;
            _path = path;
            _queryString = queryString;
        }

        /// <summary>
        /// 将异常信息写入日志文件
        /// </summary>
        public void WriteFile()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/Log/");
                String fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Path.Combine(filePath, fileName), true, System.Text.Encoding.UTF8))
                {
                    sb.Append("\r\n=========================================");
                    sb.AppendFormat("\r\nTime::{0}", DateTime.Now.ToString());
                    sb.AppendFormat("\r\nHost::{0}", _host);
                    sb.AppendFormat("\r\nUrl::{0}", _path);
                    sb.AppendFormat("\r\nQueryString::{0}", _queryString);
                    //sb.AppendFormat("\r\nIP::{0}", HttpContext.Current.Request.Host.ToString());
                    //sb.AppendFormat("\r\nUrl::{0}", HttpContext.Current.Request.Path.ToString());
                    //sb.AppendFormat("\r\nRef::{0}", HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.ToString() : String.Empty);
                    sb.Append("\r\n" + _exc.Message.ToString());
                    sb.Append("\r\n=========================================");
                    sw.Write(sb.ToString());
                }
            }
            catch { }
        }
    }
}